package com.wanchuang.shengfubao.module.login;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.wanchuang.shengfubao.MainActivity;
import com.wanchuang.shengfubao.R;
import com.wanchuang.shengfubao.base.BaseActivity;
import com.wanchuang.shengfubao.base.MainApplication;
import com.wanchuang.shengfubao.dialog.ActionDialog;
import com.wanchuang.shengfubao.dialog.BaseDialog;
import com.wanchuang.shengfubao.help.UserBean;
import com.wanchuang.shengfubao.help.UserHelper;
import com.wanchuang.shengfubao.net.Apis;
import com.wanchuang.shengfubao.net.NetworkManager;
import com.wanchuang.shengfubao.net.WebApis;

import com.wanchuang.shengfubao.net.interfaces.OnRequestCallBack;
import com.wanchuang.shengfubao.proto.Index;
import com.wanchuang.shengfubao.proto.LoginOuterClass;
import com.wanchuang.shengfubao.proto.MemberOuterClass;
import com.wanchuang.shengfubao.utils.APKVersionCodeUtils;
import com.wanchuang.shengfubao.utils.StatusBarUtil;
import com.wanchuang.shengfubao.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kale.ui.view.dialog.EasyDialog;

import static androidx.camera.core.CameraX.getContext;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.phone_et)
    EditText loginAccountEdt;
    @BindView(R.id.tv_welcome)
    TextView tvWelcome;
    @BindView(R.id.password_et)
    EditText loginPwdEdt;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.login_cb_password)
    CheckBox loginCbPassword;

    private long mExitTime;

    private int isrenzheng = 0;
    private int INSTALL_PERMISS_CODE = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);
        ButterKnife.bind(this);
        setPasswordCanSee();
        setAccountEt();
        checkVersion();
        tvWelcome.setText("欢迎登录" + getString(R.string.app_name));
    }

    private void setAccountEt() {
        loginPwdEdt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                login();
                return true;
            }
            return false;
        });
        String phone = getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(phone)) {
            loginAccountEdt.setText(phone);
            loginAccountEdt.setSelection(phone.length());//将光标移至文字末尾
        }
    }


    private void login() {
        InputMethodManager manager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager != null)
            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        String account = loginAccountEdt.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast("请输入手机号");
            return;
        }
        String pwd = loginPwdEdt.getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            showToast("请输入登录密码");
            return;
        }
        showProgress();
        LoginOuterClass.Login.Builder builder = LoginOuterClass.Login.newBuilder();
        builder.setUsername(account).setPassword(pwd).setClient("android");
        NetworkManager.INSTANCE.post(Apis.login, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                loginSuccess(LoginOuterClass.Login.parseFrom(bytes));
                identification();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void loginSuccess(LoginOuterClass.Login respon) {
        showToast("登录成功");
        UserBean userBean = new UserBean();
        userBean.setKey(respon.getKey());
        userBean.setChat_id(respon.getChatId());
        userBean.setChat_pwd(respon.getChatPwd());
        userBean.setPush_id(respon.getPushId());
        UserHelper.login(userBean);
    }

    /**
     * 设置密码是否为明文显示
     */
    private void setPasswordCanSee() {
        loginCbPassword.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                //设置为密文显示
                loginPwdEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                //设置为明文显示
                loginPwdEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            //光标在最后显示
            loginPwdEdt.setSelection(loginPwdEdt.length());
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MainApplication.finishAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 验证是否进行实名认证
     */
    private void identification() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                hideProgress();
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                UserBean userBean = new UserBean();
                userBean.setIs_approve(member.getIsApprove());
                userBean.setIs_bank(member.getIsBank());
                userBean.setTruename(member.getTruename());
                UserHelper.syncCurrentUserInfo(userBean);
                if (member.getIsApprove() == isrenzheng) {
                    showToast("请先进行实名认证");
                    WebViewActivity.startActivity(mContext, WebApis.Verification);
                } else {
                    if (member.getIsBank() == 0) {
                        WebViewActivity.startActivity(mContext, WebApis.bindBankCard + "?user_name=" + member.getTruename());
                    } else {
                        startActivity(MainActivity.class);
                    }
                    finish();
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }


    @OnClick({R.id.login_btn, R.id.forget_password_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                isrenzheng = 0;
                login();
                break;
            case R.id.forget_password_tv:
                Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
                intent.putExtra("title", "忘记密码");
                startActivityForResult(intent, 100);
                break;

        }
    }


    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVerison(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }


    private void checkVerison(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("请允许安装未知来源权限");
                    builder.setCancelable(false);
                    builder.setOnDismissListener(dialog -> {
                    });
                    builder.setNegativeButton("", (dialog, which) -> {

                    });
                    builder.setPositiveButton("设置", (dialog, which) -> {
                        startInstallPermissionSettingActivity();
                        finish();
                    });
                    builder.show();
                } else {
                    DownloadBuilder builder = AllenVersionChecker
                            .getInstance()
                            .downloadOnly(crateUIData(versionBean));
                    builder.setCustomVersionDialogListener(createCustomDialogOne());
                    if (versionBean.getForce().equals("1")) {
                        builder.setForceUpdateListener(MainApplication::finishAllActivity);
                    }
                    builder.setForceRedownload(true).executeMission(mContext);
                }
            } else {
                DownloadBuilder builder = AllenVersionChecker
                        .getInstance()
                        .downloadOnly(crateUIData(versionBean));
                builder.setCustomVersionDialogListener(createCustomDialogOne());
                if (versionBean.getForce().equals("1")) {
                    builder.setForceUpdateListener(MainApplication::finishAllActivity);
                }
                builder.setForceRedownload(true).executeMission(mContext);
            }
        }
    }


    private UIData crateUIData(Index.get_app_version_info versionBean) {
        UIData uiData = UIData.create();
        uiData.setTitle(versionBean.getTitle());
        uiData.setDownloadUrl(versionBean.getDownloadUrl());
        uiData.setContent(versionBean.getContext());
        uiData.getVersionBundle().putString("force", versionBean.getForce());
        return uiData;
    }


    /**
     * 务必用库传回来的context 实例化你的dialog
     * 自定义的dialog UI参数展示，使用versionBundle
     *
     * @return
     */
    private CustomVersionDialogListener createCustomDialogOne() {
        return (context, versionBundle) -> {
            BaseDialog baseDialog = new BaseDialog(context, R.style.BaseDialog, R.layout.custom_dialog_layout);
            TextView textView = baseDialog.findViewById(R.id.tv_msg);
            TextView title = baseDialog.findViewById(R.id.tv_title);
            ImageView canCle = baseDialog.findViewById(R.id.versionchecklib_version_dialog_cancel);
            if (versionBundle.getVersionBundle().getString("force").equals("1"))
                canCle.setVisibility(View.GONE);
            textView.setText(versionBundle.getContent());
            title.setText(versionBundle.getTitle());
            return baseDialog;
        };
    }

    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, INSTALL_PERMISS_CODE);
    }


    private void showAlert() {
        Index.get_agreement.Builder builder = Index.get_agreement.newBuilder();
        builder.setType("act_alert");
        NetworkManager.INSTANCE.post(Apis.get_agreement, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_agreement agreement = Index.get_agreement.parseFrom(response);
                Log.e("mango", "onOk: " + agreement);
                if (agreement.getActState().equals("1")) {
                    ActionDialog.Builder builder = new ActionDialog.Builder(mContext);
                    builder.setContent(agreement.getContent());
                    EasyDialog build = builder.build();
                    build.show(getSupportFragmentManager());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }


}
